//
//  NetworkTools.swift
//  swift封装afn
//
//  Created by Apple on 15/10/22.
//  Copyright © 2015年 miao. All rights reserved.
//

import UIKit
import AFNetworking


//MARK: -请求方法枚举
///枚举，post ,get
enum HMRequestMethod: String{
    case GET = "GET"
    case POST = "POST"
    
}

//MARK: -OAuth授权url


//MARK:网络工具
class NetworkTools: AFHTTPSessionManager {
    
    //MARK: -应用程序信息
    private let appKey = "3381672028"
    private let appSecret = "4e2366b7823dfb3902c4e9d59b7ec038"
    private let redirectURL = "http://www.baidu.com"

    /// 网络请求完成回调 , 类似oc中的typedef
    typealias HMRequestCallBack = (result:AnyObject?, error: AnyObject?)->()
    
    /// 单例
    static let shareTools: NetworkTools = {
       
        let tools = NetworkTools(baseURL: nil)
        
        //反序列化的支持方式
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    ///MARK: 设置token字典
    private var tokenDict: [String: AnyObject]? {
        
        if let token = AccountViewModel.shareAccountViewModel.accessToken{
            
            return ["access_token":token]
            
        }
        return nil
    }
  
}
//MARK: -加载用户信息
extension NetworkTools{
    func loadUserAccountInfo(uid: String,finished:HMRequestCallBack){
        
        //获取字典
        guard var  param = tokenDict else{
            //如果为空,发送通知
            finished(result: nil, error: NSError(domain: "it.cast.com", code: -1001, userInfo: ["message":"token无效"]))
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
         param["uid"] = uid
        ///URLString   url
        ///parameter   接口参数
        ///finished    完成回调
        request(HMRequestMethod.GET, URLString: urlString, parameters: param, finished: finished)
        
    }
}

//MARK: -OAuth 授权相关方法
extension NetworkTools{
    
    /// OAuth 授权url
    /// -see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURL)"
        return NSURL(string: urlString)!
    }
    
    //MARK: -加载token
    ///-see :[http://open.weibo.com/wiki/OAuth2/access_token](http://open.weibo.com/wiki/OAuth2/access_token)
   
    func loadAccessToken(code: String, finished:HMRequestCallBack){
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        let param = ["client_id":appKey,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectURL]
        request(HMRequestMethod.POST, URLString: urlStr, parameters: param, finished: finished)
        //从网络返回的数据是二进制数据，AFN 默认是json 直接反序列化
        //而AFHttpResponseSerializer,默认是二进制数据
        
//        responseSerializer = AFHTTPResponseSerializer()
//        POST(urlStr, parameters: param, success: { (_, result) -> Void in
//            let json = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
//            print(json)
//            }, failure: nil)
    }
}

//MARK: 封装请求方法
extension NetworkTools{

   private func request(method: HMRequestMethod, URLString: String, parameters:[String:AnyObject]?,finished:HMRequestCallBack){
        
        //成功的回调准备代码
        let success = { (task:NSURLSessionDataTask, result:AnyObject) -> Void in
            
            finished(result: result, error: nil)
        }
        // 失败的回调
        let failure = { (task: NSURLSessionDataTask,error: NSError) -> Void in
            
            print(error)
            finished(result: nil, error: error)
        }
        
        if method == HMRequestMethod.GET{
         
            GET(URLString, parameters: parameters, success: success, failure: failure)
        }else{
            
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
    }

}